clear;clc;
%% Device connection
tek=EquipmentControl.AWG.TektronixAFG3252('visa-usb',  'TCPIP0::192.168.1.101::inst0::INSTR');

obj1 = instrfind('Type', 'serial', 'Port', 'COM3', 'Tag', '');
if isempty(obj1)
    obj1 = serial('COM3');
else
    fclose(obj1);
    obj1 = obj1(1);
end
fopen(obj1);
set(obj1, 'Terminator', {'CR','CR'});

%% TEK sin wave with noise
tek.setWave(1, 'shape', 'PRN', 'amplitude', 1.0);
tek.setBurstState(1, 'OFF');
tek.fire(1);

%% Set SR785 and fetch data
% SR785 Settings: Freq Span 0...400Hz, 400 lines, acq time 1s, 
% base freq 102.4 kHz
% Measurement: FFT1, Average: RMS, linear, #aver 100
% dB Units: Off; PSD: off; Pk Units: pp
%

ampList = logspace(-1, 0.6, 10); dataAll = [];
for noise_amp = ampList
    tek.setWave(1, 'shape', 'PRN', 'amplitude', noise_amp);
    pause(0.5);

    fprintf(obj1, 'STRT');
    
    fprintf('waiting for average ...');
    while str2double(query(obj1, 'DSPS? 1'))==0
        pause(0.1);
    end
    
    fprintf('retrieving data ...');
    [flist, data] = fetchSR785(obj1);
    dataAll = [dataAll data];
end

%% Plot
figure;
subplot(1, 2, 1);
semilogy(flist, dataAll)
xlabel('Frequency [Hz]');
ylabel('Averaged Noise Amplitude [Vpp]');
title('50 average, acq time 0.5s, freq span 0...1.6Hz, 800 lines');

subplot(1, 2, 2);
bgNoise = mean(dataAll(300:700, :), 1);
loglog(ampList, bgNoise, 'bo-');
xlabel('Generated Noise Amplitude [V]');
ylabel('Measured Noise Amplitude [Vpp]');

%% Disconnect and Clean Up
fclose(obj1);